package ywpt.core.util;
import java.io.*;
public class FileTools {
	public FileTools() {
	}
	public static int copyStream(InputStream in, OutputStream out) throws IOException {
		int result = 0;
		byte buf[] = new byte[4096];
		int numRead;
		while ((numRead = in.read(buf)) != -1) {
			out.write(buf, 0, numRead);
			result += numRead;
		}
		out.flush();
		return result;
	}
	public static byte[] getStreamBytes(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		copyStream(in, out);
		return out.toByteArray();
	}
	public static void createDir(String dirName) {
		String dirList[] = dirName.split("[//\\\\]");
		String tmp = "";
		for (String element : dirList) {
			tmp = tmp + element + "/";
			File fp = new File(tmp);
			if (!fp.isDirectory() && !fp.isFile()) {
				fp.mkdir();
			}
		}
	}
	public static void deleteDir(String dirName) {
		File fp = new File(dirName);
		File aa[] = fp.listFiles();
		for (File element : aa) {
			if (element.isFile()) {
				element.delete();
			} else if (element.isDirectory()) {
				deleteDir(element.getPath());
			}
		}
		fp.delete();
	}
	public static void delFile(String fileName) {
		File fp = new File(fileName);
		if (fp.isFile()) {
			fp.delete();
		}
	}
	public static void delFile(String fileName[]) {
		if (fileName == null) {
			return;
		}
		for (String element : fileName) {
			delFile(element);
		}
	}
	public static int copyFile(String fromFile, String toFile) throws FileNotFoundException, IOException {
		InputStream is = new FileInputStream(fromFile);
		OutputStream os = new FileOutputStream(toFile);
		int ret = copyStream(is, os);
		is.close();
		os.close();
		return ret;
	}
	public static int copyToFile(InputStream in, String toFile) throws FileNotFoundException, IOException {
		OutputStream os = new FileOutputStream(toFile);
		int ret = copyStream(in, os);
		os.close();
		return ret;
	}
	static String convertFileSize(Long size) {
		int divisor = 1;
		String unit = "bytes";
		if (size >= 0x100000L) {
			divisor = 0x100000;
			unit = "MB";
		} else if (size >= 1024L) {
			divisor = 1024;
			unit = "KB";
		}
		if (divisor == 1) {
			return size / divisor + " " + unit;
		}
		String aftercomma = String.valueOf((100L * (size % divisor)) / divisor);
		if (aftercomma.length() == 1) {
			aftercomma = "0" + aftercomma;
		}
		return size / divisor + "." + aftercomma + " " + unit;
	}
}
